﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Web.UI;
using System.Web.UI.WebControls;
using MLY.Bll;

namespace MLY.LTR
{
  public partial class gridBasePage : Bll.BasePage
  {
    // TYPES FOR GENERIC SORT COLUMNS - NEEDS TO FIT THE ACTUAL COLUMNS!
    protected DbType[] gridColTypes = {DbType.String,DbType.String,DbType.String,DbType.DateTime,
                                              DbType.DateTime,DbType.DateTime,
                                              DbType.Int32,DbType.DateTime,DbType.Int32,DbType.String,DbType.String
                                 ,DbType.String,DbType.String,DbType.String,DbType.String,DbType.Int32};

    protected string CurrentlyLoadedControls
    {
      get
      {
        if (Session["CURRENTLY_LOADED_CONTROL"] != null)
          return Session["CURRENTLY_LOADED_CONTROL"].ToString();
        return "";
      }
      set
      {
        Session["CURRENTLY_LOADED_CONTROL"] = value;
      }
    }

    private string Specialwhere
    {
      get
      {
        if (Session["whereClause"] != null)
          return Session["whereClause"].ToString();
        return "";
      }

      set
      { 
        Session["whereClause"] = value; 
      }
    }

    protected string CustomerId
    {
      get
      {
        if (Session["CustomerId"] == null)
          return "";
        return Session["CustomerId"].ToString();
      }
      set
      {
        Session["CustomerId"] = value;
      }
    }

    protected string ContractorID
    {
      get
      {
        if (Session["ContractorID"] == null)
          return "";
        return Session["ContractorID"].ToString();
      }
      set
      {
        Session["ContractorID"] = value;
      }
    }

    protected int SplitOrderNum
    {
      get
      {
        if (Session["splitOrderNum"] == null)
          return -1;
        return int.Parse(Session["splitOrderNum"].ToString());
      }
      set
      {
        Session["splitOrderNum"] = value;
      }
    }

    protected int pageNum
    {
      get
      {
        if (Session["pageNum"] == null)
          return 0;
        return int.Parse(Session["pageNum"].ToString());
      }
      set
      {
        Session["pageNum"] = value;
      }
    }

    protected SortDirection sortDirection
    {
      get
      {
        if (Session["sortDirection"] == null)
          return 0;
        return (SortDirection)Session["sortDirection"];
      }
      set
      {
        Session["sortDirection"] = value;
      }
    }

    protected string sortExpression
    {
      get
      {
        if (Session["sortExpression"] == null)
          return "";
        return Session["sortExpression"].ToString();
      }
      set
      {
        Session["sortExpression"] = value;
      }
    }

    protected bool isSorted
    {
      get
      {
        if (Session["isSorted"] == null)
          return false;
        return (bool)Session["isSorted"];
      }
      set
      {
        Session["isSorted"] = value;
      }
    }

    public bool isClient
    {
      get
      {
        if (Session["IsClient"] == null)
          return false;
        return (bool)Session["IsClient"];
      }
      set
      {
        Session["IsClient"] = value;
        if (value)
          HyperLinkAddNew.NavigateUrl = @"~/LTR/Contractors/ContractoraddWoFrm.aspx";
        else
          HyperLinkAddNew.NavigateUrl = @"~/LTR/Clients/ClientaddWoFrm.aspx";
      }
    }

    public decimal GetInventoryBalance(int WorkOrderId)
    {
      BalanceType targetDate = BalanceType.ByRequestedDate;
      if (this.ddlCalcField.SelectedValue == "PlannedDate")
      {
        targetDate = BalanceType.ByPlannedDate;
      }
      return MLY.Bll.clsWorkOrder.GetInventoryBalance(WorkOrderId, targetDate);
    }

    public virtual void SetDatasourceToDefault()
    {
      if (isClient)
        Specialwhere = null;
      GridView1.DataSource = null;
      GridView1.DataSourceID = "LinqDataSource1";
      if (CustomerId != "")
        LinqDataSource1.Where = "  (CustomerId == " + CustomerId + ")";
      if (ContractorID != "")
      {
        if (LinqDataSource1.Where != "")
          LinqDataSource1.Where += " && ";
        LinqDataSource1.Where += " (ContractorId == " + ContractorID + ")";
      }

      // ELIMINATE CANCELED ROWS
      DateTime now = new DateTime(2099, 1, 1);
      LinqDataSource1.Where += " && (ActualDelivaryDate.Value.CompareTo(  " + '"' + now.ToString() + '"' + ") == -1 || ActualDelivaryDate == null) && (originalWoForDist == null)";
      LinqDataSource1.OrderBy = String.Format(@"{0} (ActualDelivaryDate == NULL ? 0 : 1) desc, ActualDelivaryDate desc", String.IsNullOrEmpty(sortExpression) ? "" : sortExpression + " " + sortDirection + " , ");
      GridView1.DataBind();
    }

    void fillDropDown()
    {
      if (ddlColumnList.Items.Count <= 1)
      {
        int colNum = GridView1.Columns.Count;
        string[] retVal = new string[colNum];
        for (int i = 2; i < colNum; i++)
        {
          ListItem l = new ListItem();
          if (GridView1.Columns[i] is TemplateField)
          {
            TemplateField t = (TemplateField)GridView1.Columns[i];
            Control c = new Control();
            if (t.HeaderTemplate == null)
              continue;
            t.HeaderTemplate.InstantiateIn(c);
            foreach (var item in c.Controls)
            {
              if (item is LinkButton)
              {
                l = new ListItem(((LinkButton)item).Text, ((LinkButton)(item)).CommandArgument);
                ddlColumnList.Items.Add(l);
              }
            }
          }
          else
          {
            l = new ListItem(GridView1.Columns[i].HeaderText, GridView1.Columns[i].SortExpression);
            ddlColumnList.Items.Add(l);
          }
        }
      }
    }

    void loadFilter()
    {
      String ContentID = CurrentlyLoadedControls;

      if (!String.IsNullOrEmpty(ContentID))
      {
        string[] ContentIdSplits = ContentID.Split(',');
        foreach (string s in ContentIdSplits)
        {
          string[] args = s.Split('_');
          DynamicLoadControl(args[0], int.Parse(args[1]));
        }
      }
    }

    void bindGrid()
    {
      if (Specialwhere != "")
      {
        GridView1.DataSourceID = "dynamicWhereObjectSource";
        GridView1.DataBind();
      }
      else
      {
        SetDatasourceToDefault();
        GridView1.DataBind();
      }
      DataBind();
    }

    void showMsg(string msg, Exception ex, bool isError)
    {
      ErrLbl.Text = Dictionary.Translate(msg);
      Bll.tblLogger.AddLogEntry(String.Format("User {0} had Error: {1}", Session["organizationId"], ex.Message), isError);
    }

    private void DynamicLoadControl(string colName, int colTypeIdx)
    {
      try
      {
        DbType currDbType = gridColTypes[colTypeIdx];

        Control ctrl = this.LoadControl(Request.ApplicationPath + "/UserControls/columnsorter.ascx", new object[] { colName, currDbType });
        ((UserControls.columnSorter)ctrl).clickedX += new EventHandler(clientWoGrid_clickedX);

        advancedSortPanel.Controls.Add(ctrl);
      }
      catch (Exception ex)
      {
        throw ex;
      }
    }

    void clientWoGrid_clickedX(object sender, EventArgs e)
    {
      string[] ctrls = CurrentlyLoadedControls.Split(',');
      CurrentlyLoadedControls = "";
      foreach (string s in ctrls)
      {
        if (!s.Contains(((UserControls.columnSorter)sender).colName))
          CurrentlyLoadedControls += s + ",";
      }
      if (CurrentlyLoadedControls != "")
        CurrentlyLoadedControls = CurrentlyLoadedControls.Remove(CurrentlyLoadedControls.Length - 1);
      advancedSortPanel.Controls.Remove((Control)sender);

      if (advancedSortPanel.Controls.Count == 0)
        Specialwhere = "";

      if (!String.IsNullOrEmpty(Specialwhere))
      {
        evalFilter();
      }

      bindGrid();
      ddlColumnList.SelectedIndex = 0;
    }

    private UserControl LoadControl(string UserControlPath, params object[] constructorParameters)
    {
      List<Type> constParamTypes = new List<Type>();
      foreach (object constParam in constructorParameters)
      {
        constParamTypes.Add(constParam.GetType());
      }

      UserControl ctl = Page.LoadControl(UserControlPath) as UserControl;

      // Find the relevant constructor
      ConstructorInfo constructor = ctl.GetType().BaseType.GetConstructor(constParamTypes.ToArray());

      // And then call the relevant constructor
      if (constructor == null)
      {
        throw new MemberAccessException("The requested constructor was not found on : " + ctl.GetType().BaseType.ToString());
      }
      else
      {
        constructor.Invoke(ctl, constructorParameters);
      }
      return ctl;
    }

    protected void Page_Load(object sender, EventArgs e)
    {
      if (!this.IsPostBack && Request.QueryString["doPostBack"] == null)
      {
        if (Request.ServerVariables["HTTP_REFERER"] != null)
          ViewState["Referer"] = Request.ServerVariables["HTTP_REFERER"];
        else
          ViewState["Referer"] = this.Request.Url.ToString();

        using (Dal.lqKbmDataContext dc = new MLY.Dal.lqKbmDataContext())
        {
          relations = dc.TableOrganizationRelations.ToList();
        }
        Specialwhere = "";
        CurrentlyLoadedControls = "";
      }

      ContractorID = CustomerId = "";

      fillDropDown();
      setClient();
      ErrLbl.Text = "";

      loadFilter();
      if (Request.QueryString["split"] != null)
        doSplit();
      bindGrid();
      editDistBtn.Click += new EventHandler(editDistBtn_Click);
    }

    void editDistBtn_Click(object sender, EventArgs e)
    {

      var distId = hiddenDistToEdit.Value;
      var quantity = sentQuantToEditTxt.Text;
      var planned = distPlannedDateTxt.Text;
      var actual = distActualDateTxt.Text;
      Bll.Bl_Dist.editDist(distId, quantity, actual, planned);
      Response.RedirectTo(Request.Url.ToString());
    }

    public List<Dal.TableOrganizationRelation> relations
    {
      get
      {
        return Session["relations"] == null ? null : (List<Dal.TableOrganizationRelation>)Session["relations"];
      }
      set
      {
        Session["relations"] = value;
      }
    }

    void setClient()
    {
      if (Request.QueryString["IsClient"] != null)
      {
        if (Request.QueryString["ContractorId"] != null)
          ContractorID = Request.QueryString["ContractorId"].ToString();
        CustomerId = SessParam.OrganizationId.ToString();
        isClient = true;
      }
      else
      {
        if (Request.QueryString["ClientID"] != null)
          CustomerId = Request.QueryString["ClientID"].ToString();
        ContractorID = SessParam.OrganizationId.ToString();
        isClient = false;
      }
    }

    protected void columnListDdl_SelectedIndexChanged(object sender, EventArgs e)
    {
      if (ddlColumnList.SelectedIndex > 0)
      {
        string colName = ddlColumnList.SelectedValue;
        DynamicLoadControl(colName, ddlColumnList.SelectedIndex - 1);
        if (!String.IsNullOrEmpty(CurrentlyLoadedControls))
          CurrentlyLoadedControls += ",";
        CurrentlyLoadedControls += String.Format("{0}_{1}", colName, ddlColumnList.SelectedIndex - 1);
      }
      ddlColumnList.SelectedIndex = 0;
    }

    protected void ddlCalcField_SelectedIndexChanged(object sender, EventArgs e)
    {
    }


    void evalFilter()
    {
      try
      {
        if (advancedSortPanel.Controls.Count == 0)
        {
          Specialwhere = String.Empty;
          return;
        }
        Specialwhere = "";
        if (!isClient)
        {
          Specialwhere = String.Format(" ContractorId = {0}  ", SessParam.OrganizationId
           );
          if (CustomerId != "")
            Specialwhere += "And CustomerId = " + CustomerId;
        }
        else
        {
          Specialwhere = String.Format(" CustomerId = {0}", SessParam.OrganizationId);
          if (ContractorID != "")
            Specialwhere += "And ContractorId = " + ContractorID;
        }

        foreach (Control c in advancedSortPanel.Controls)
          if (c is UserControls.columnSorter)
          {
            string wh = (c as UserControls.columnSorter).getWhere(!isClient);
            if (wh != "")
              Specialwhere += " AND " + wh;
          }
      }
      catch (Exception ex)
      {
        SetDatasourceToDefault();
        showMsg("Filtering unsuccessfull", ex, true);
      }
    }

    protected void Unnamed1_Click(object sender, EventArgs e)
    {
      evalFilter();
      bindGrid();
    }

    protected void ClearClick(object sender, EventArgs e)
    {
      Specialwhere = "";
      CurrentlyLoadedControls = "";
      advancedSortPanel.Controls.Clear();
      SetDatasourceToDefault();
    }

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
      Dal.TableWorkOrder to = (Dal.TableWorkOrder)e.Row.DataItem;
      Dal.TableOrganizationRelation rel;
      int h;
      if (e.Row.Cells.Count >= 2 && e.Row.RowIndex >= 0)
      {
        if (isClient)
        {
          rel = relations.Where(S => S.ContractorId == to.ContractorId && S.CustomerId == SessParam.OrganizationId
              ).FirstOrDefault();
        }
        else
        {
          rel = relations.Where(S => S.CustomerId == to.CustomerId && S.ContractorId == SessParam.OrganizationId
          ).FirstOrDefault();
        }
        try
        {
          if (rel != null)
          {
            if ((to.RequestedDelivaryDate.Value - to.SendDate.Value).Days < rel.DefaultTimeDurationDays / 9 )
              e.Row.BackColor = System.Drawing.Color.FromArgb(255, 140, 140);
          }
        }
        catch //(Exception ex)
        { }
        e.Row.Attributes["onmouseover"] = "this.style.cursor='pointer';";
        e.Row.Attributes["onmouseout"] = "this.style.cursor='default';";

        if (int.TryParse(GridView1.DataKeys[e.Row.RowIndex].Values[0].ToString(), out h))
        {
          if (h == SplitOrderNum)
          {
            ((MultiView)(e.Row.Cells[1].Controls[1])).ActiveViewIndex = 1;
          }
        }
      }

      try
      {
        Repeater myRep = e.Row.Cells[6].Controls[1] as Repeater;
        if (myRep != null)
        {
          myRep.DataSource = Bll.Bl_Dist.getDist(to.WorkOrderId);
          myRep.DataBind();
        }
      }
      catch //(Exception ex)
      {
      }
    }

    protected void splitSubmit_Click(object sender, EventArgs e)
    {
      GridViewRow gr = (GridViewRow)((Control)sender).NamingContainer;
      MultiView m = ((MultiView)gr.Cells[1].Controls[1]);
      View n = m.Views[1];
      decimal howMuchToSplit = decimal.Parse(splitHidden.Value);
      Bll.clsWorkOrder w = new MLY.Bll.clsWorkOrder(SplitOrderNum);
      try
      {
        w.Split(Convert.ToDecimal(howMuchToSplit));
        SplitOrderNum = -1;
        GridView1.DataBind();
      }
      catch (Exception ex)
      {
        ErrLbl.Text = ex.Message;
      }
    }

    void doSplit()
    {
      GridViewRow gr = null;
      foreach (GridViewRow item in GridView1.Rows)
      {
        if (((MultiView)item.Cells[1].Controls[1]).ActiveViewIndex == 1)
        {
          gr = item;
          break;
        }
      }
      MultiView m = ((MultiView)gr.Cells[1].Controls[1]);
      View n = m.Views[1];
      decimal howMuchToSplit = decimal.Parse(((TextBox)n.Controls[3]).Text);
      Bll.clsWorkOrder w = new MLY.Bll.clsWorkOrder(SplitOrderNum);
      try
      {
        w.Split(Convert.ToDecimal(howMuchToSplit));
        SplitOrderNum = -1;
        GridView1.DataBind();
        m.ActiveViewIndex = 0;
      }
      catch (Exception ex)
      {
        ErrLbl.Text = ex.Message;
      }
      finally
      {
      }
    }

    protected void GridView1_PageIndexChanged(object sender, EventArgs e)
    {
    }

    protected void CancelSplitClicked(object sender, EventArgs e)
    {
      SplitOrderNum = -1;
      bindGrid();
    }

    protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
    {
      if (!isSorted)
      {
        sortDirection = e.SortDirection;
        sortExpression = e.SortExpression;
        isSorted = true;
        GridView1.Sort(sortExpression, sortDirection);
      }
    }

    protected void cancelSort_Click(object sender, EventArgs e)
    {
    }

    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
    }

    protected void SplitImageButtonClicked(object sender, ImageClickEventArgs e)
    {
      SplitOrderNum = int.Parse(((ImageButton)sender).CommandArgument);
      bindGrid();
    }

    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
      switch (e.CommandName.ToLower())
      {
        case "attach":
          break;
      }
    }

    protected void LinqDataSource1_Deleting(object sender, LinqDataSourceDeleteEventArgs e)
    {
    }

    protected void delWoBtn_Click(object sender, ImageClickEventArgs e)
    {
      Bll.clsWorkOrder w = new MLY.Bll.clsWorkOrder(int.Parse(((ImageButton)sender).CommandArgument));
      w.Data.ActualDelivaryDate = Utils.CanceledDate;
      w.Save();
      GridView1.DataBind();
    }
  }
}